<template>
  <div class="img_box">
    <template v-if="userAuth[routeName].authorityUpload">
      <el-input size="mini" v-model="bz" placeholder="请输入备注">
        <el-button size="mini" slot="append" @click="handleFileChange">保存</el-button>
      </el-input>
      <div class="input_box">
        <!-- 不填备注就隐藏input -->
        <input v-if="uploadStatus == 0" id="imgFile" @change="onChange" type="file" ref="imginputer" accept="image/*" />
        <label for="imgFile" class="label_img" @click="labelClick"></label>
        <img :src="imgBase64 || imgURL" />
      </div>
    </template>
    <template v-else>
      <el-input disabled size="mini" placeholder="请输入备注">
        <el-button size="mini" disabled slot="append">保存</el-button>
      </el-input>
      <div class="input_box" style="cursor: not-allowed;">
        <!-- 不填备注就隐藏input -->
        <img :src="imgURL" />
      </div>
    </template>
  </div>
</template>

<script>
  // import axios from 'axios'
  import {uploadImgDept, uploadImgCar, uploadImgMaintenance, uploadImgGoodsOut, uploadImgGoodsIn, uploadImgGoodsCheck, uploadImgCheckCar, uploadImgDriveCost} from '@/api/api'
  import {mapGetters} from 'vuex'
  export default {
    name: 'imgUpload',
    props: {
      value: {
        // 绑定默认的value prop
        default: undefined
      },
      /**
       * 类型 car staff carMaintenance goodsOut goodsIn carCheck driveCost
       */
      type: {
        type: String,
        default: 'car'
      },
      id: {
        type: Number,
        default: null
      }
    },
    data () {
      return {
        loading: false, // 是否正在上传
        bz: '', // 备注
        file: '', // 文件
        imgURL: require('@/assets/upload.jpg'),
        imgBase64: '',
        routeName: this.$route.name, // 路由名称
      }
    },
    computed: {
      // 上传状态  0 可上传  1未填写备注  2备注包含特殊字符  3 上传中
      uploadStatus() {
        if (this.bz == '') {
          return 0
        } else {
          if (!/^[A-Za-z0-9\u4e00-\u9fa5]+$/.test(this.bz)) { // 正则匹配字母、数字、汉字
            return 2
          } else {
            if (this.loading) {
              return 3
            } else {
              return 0
            }
          }
        }
      },
      ...mapGetters(['userAuth']),
    },
    methods: {
      labelClick(e) {
        if (this.uploadStatus == 2) {
          this.$alert('备注不能包含特殊符号', '提示', {
            confirmButtonText: '确定',
            callback: action => {
            }
          })
        }
      },
      async uploadImg(formdata, id, bz) {
        let res
        if (this.type == 'car') {
          res = await uploadImgCar(formdata, id, bz)
        } else if (this.type == 'staff') {
          res = await uploadImgDept(formdata, id, bz)
        } else if (this.type == 'carMaintenance') {
          res = await uploadImgMaintenance(formdata, id, bz)
        } else if (this.type == 'goodsOut') {
          res = await uploadImgGoodsOut(formdata, id, bz)
        } else if (this.type == 'goodsIn') {
          res = await uploadImgGoodsIn(formdata, id, bz)
        } else if (this.type == 'goodsCheck') {
          res = await uploadImgGoodsCheck(formdata, id, bz)
        } else if (this.type == 'carCheck') {
          res = await uploadImgCheckCar(formdata, id, bz)
        } else if (this.type == 'driveCost') {
          res = await uploadImgDriveCost(formdata, id, bz)
        }
        return res
      },
      onChange(e) {
        let file = e.target.files[0]
        this.file = file
        this.imgPreview(file)
      },
      async handleFileChange () {
        // let e = this.$refs['imginputer']
        // let inputDom = this.$refs.imginputer
        // 获取文件数据
        if (!this.file) {
          this.$message({message: '请选择文件'})
          return
        }
        if (this.uploadStatus !== 0) {
          return
        }
        let size = Math.floor(this.file.size / 1024 / 1024)
        // 文件大小
        if (size > 2) {
          this.$message({message: '请选择小于2M的图片'})
          return false
        }

        let formdata = new FormData()
        formdata.append('file', this.file, 'fileName')
        this.loading = true
        let res = await this.uploadImg(formdata,this.id,this.bz)
        this.loading = false
        this.clearInput() // 清除input
        if (res.code === 0) {
          this.$message('上传成功')
          this.bz = ''
          this.file = ''
          this.imgBase64 = ''
          this.$emit('success')
        } else {
          this.$message(res.msg || '上传失败，请重新上传')
        }
      },
      /**
       * 清除input
       */
      clearInput() {
        setTimeout(() => {
          let inputDom = this.$refs.imginputer
          if (inputDom) {
            console.log(inputDom)
            console.log(typeof inputDom)
            if (inputDom.hasOwnProperty('files')) {
              inputDom.files.length = 0
            }
          }
        }, 50);
      },
      imgPreview (file) {
        let self = this
        let windowURL = window.URL || window.webkitURL
        if (/^image/.test(file.type)) {
          // 创建一个 reader实例
          let reader = new FileReader()
          // 将图片转为 base64格式
          reader.readAsDataURL(file)
          // 读取成功后的处理
          reader.onload = (e) => {
            // self.urldata = e.target.result
            self.imgBase64 = e.target.result
          }
          // self.uploadImg = windowURL.createObjectURL(file)
        }
      },
      async uploadFormData (file) {
        // 创建一个 formdata
        let formdata = new FormData()
        formdata.append('file', file)
        // 请求配置
       // let config = {headers: {'Content-type': 'multipart/form-data'}}
        let res = await uploadImg(file)
        console.log(res)
        // axios.posts('/upload', formdata, config).then((res) => {
        //   console.log(res)
        // })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .img_box{
    position: relative;
    width: 150px;
    height: 178px;
  }
  .input_box {
    position: relative;
    width: 150px;
    height: 150px;
    // border: 1px dashed #000000;
    // border-radius: 20px;
    overflow: hidden;
    img{
      width: 150px;
      height: 150px;
    }
  }
  input{
    position: absolute;
    left: -99999px;
  }
  .label_img{
    position: absolute;
    top: 0;left: 0;right: 0;bottom: 0;
    z-index: 10; /* 这个z-index之后说到*/
    cursor: pointer;
  }
</style>